package com.dlg.user.service.impl;

import com.dlg.commons.enums.UserType;
import com.dlg.commons.exception.DataFindException;
import com.dlg.commons.exception.DataSaveException;
import com.dlg.commons.exception.DataUpdateException;
import com.dlg.commons.util.Utils;
import com.dlg.user.dao.mysql.mappers.user.*;
import com.dlg.user.domain.user.*;
import com.dlg.user.rpc.api.vo.user.*;
import com.dlg.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;

/**
 * Created by zhangjinxia on 2017/8/16.
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private OjUserMapper userMapper;

    @Autowired
    private OjUserEnterpriseAttributeMapper userEnterpriseAttributeMapper;

    @Autowired
    private OjUserPersonalAttributeMapper userPersonalAttributeMapper;

    @Autowired
    private OjUserEnterpriseAgentAttributeMapper userEnterpriseAgentAttributeMapper;

    @Autowired
    private OjUserRelationShipMapper userRelationShipMapper;

    @Transactional
    @Override
    public OjUser register(UserRegisterRpcVo userRpcRegVo) {
        OjUser ojUser = new OjUser();
        Utils.copyNotNullObject(userRpcRegVo, ojUser);
        ojUser.setAuditStatus(Short.valueOf("0"));
        BigInteger id = addUser(ojUser);
        if (UserType.ENTERPRISE.equals(userRpcRegVo.getType())) {
            OjUserEnterpriseAttribute enterpriseAttribute = new OjUserEnterpriseAttribute();
            Utils.copyNotNullObject(userRpcRegVo, enterpriseAttribute);
            enterpriseAttribute.setId(userRpcRegVo.getEnterpriseUserRpcVo().getId());
            enterpriseAttribute.setUserId(id);
            addEnterpriseUser(enterpriseAttribute);
        } else if (UserType.PERSONAL.equals(userRpcRegVo.getType())) {
            OjUserPersonalAttribute personalAttribute = new OjUserPersonalAttribute();
            Utils.copyNotNullObject(userRpcRegVo, personalAttribute);
            personalAttribute.setId(userRpcRegVo.getPersonalUserRpcVo().getId());
            personalAttribute.setUserId(id);
            addPersonalUser(personalAttribute);
        } else {
            throw new DataSaveException("用户类型非法");
        }


        return ojUser;
    }

    @Override
    public BigInteger addEnterpriseAgent(OjUserEnterpriseAgentAttribute enterpriseAgentAttribute) {
        if (null == enterpriseAgentAttribute) {
            throw new DataSaveException("要保存的对象为空");
        }
        if (null == enterpriseAgentAttribute.getId()) {
            throw new DataSaveException("要保存的对象id为空");
        }
        if (null == enterpriseAgentAttribute.getUserEnterpriseAttributeId()) {
            throw new DataSaveException("企业用户id为空");
        }
        Short agentLevel = enterpriseAgentAttribute.getAgentLevel();
        if (agentLevel == null || agentLevel > 4 || agentLevel < 1) {
            throw new DataSaveException("代理商类型不正确");
        }
        userEnterpriseAgentAttributeMapper.save(enterpriseAgentAttribute);
        return enterpriseAgentAttribute.getId();
    }

    @Override
    public void updateUserById(OjUser ojUser) {
        if (ojUser == null) {
            throw new DataUpdateException("要更新的用户对象为空");
        }
        if (null == ojUser.getId()) {
            throw new DataUpdateException("要更新的用户对象Id为空");
        }
        userMapper.update(ojUser);
    }

    @Override
    public void updatePersonalUserByUserId(OjUserPersonalAttribute personalAttribute) {
        if (null == personalAttribute) {
            throw new DataUpdateException("要更新的个人用户为null");
        }
        if (personalAttribute.getId() == null) {
            throw new DataUpdateException("要更新的个人用户的id为空");
        }
        if (personalAttribute.getUserId() == null) {
            throw new DataUpdateException("要更新的个人用户userId为空");
        }
        if (personalAttribute.getVersion()==null){
            personalAttribute.setVersion(0l);
        }else{
            personalAttribute.setVersion(personalAttribute.getVersion()+1);
        }
        if (personalAttribute.getModifyUserId() == null) {
            personalAttribute.setModifyUserId(personalAttribute.getUserId());
        }
        userPersonalAttributeMapper.updateByUserId(personalAttribute);
    }

    @Override
    public void updateEnterpriseUserByUserId(OjUserEnterpriseAttribute enterpriseAttribute) {
        if (null == enterpriseAttribute) {
            throw new DataUpdateException("要更新的企业用户对象为null");
        }
        if (enterpriseAttribute.getUserId() == null) {
            throw new DataUpdateException("userId is null");
        }
        if (enterpriseAttribute.getVersion()==null){
            enterpriseAttribute.setVersion(0l);
        }else{
            enterpriseAttribute.setVersion(enterpriseAttribute.getVersion()+1);
        }
        if (enterpriseAttribute.getModifyUserId() == null) {
            enterpriseAttribute.setModifyUserId(enterpriseAttribute.getUserId());
        }
        userEnterpriseAttributeMapper.updateByUserId(enterpriseAttribute);
    }

    @Override
    public void updateEnterpriseAgentByUserId(OjUserEnterpriseAgentAttribute enterpriseAgentAttribute) {
        if (null == enterpriseAgentAttribute) {
            throw new DataUpdateException("要更新的代理商对象为为空！");
        }
        if (null == enterpriseAgentAttribute.getId()) {
            throw new DataUpdateException("要更新的代理商对象的id为空！");
        }
        if (null == enterpriseAgentAttribute.getUserEnterpriseAttributeId()) {
            throw new DataUpdateException("要更新的代理商对象的企业用户属性id为空！");
        }
        if (enterpriseAgentAttribute.getVersion()==null){
            enterpriseAgentAttribute.setVersion(0l);
        }else{
            enterpriseAgentAttribute.setVersion(enterpriseAgentAttribute.getVersion()+1);
        }
        OjUserEnterpriseAgentAttribute userEnterpriseAgentAttributeVo = new OjUserEnterpriseAgentAttribute();
        Utils.copyNotNullObject(enterpriseAgentAttribute,userEnterpriseAgentAttributeVo);
        userEnterpriseAgentAttributeMapper.updateById(userEnterpriseAgentAttributeVo);
    }

    public OjUser queryUserDetail(BigInteger userId) {
        OjUser user;
        if (userId == null) {
            throw new DataFindException("userId is null");
        }
        user = userMapper.findById(userId);
        if (user == null) {
            return null;
        }
        if (null == user.getType()) {
            return null;
        }
        if (user.getType().equals(UserType.PERSONAL)) {
            OjUserPersonalAttribute userPersonalAttribute = userPersonalAttributeMapper.findOneByUserId(userId);
            user.setUserPersonalAttribute(userPersonalAttribute);
        } else if (user.getType().equals(UserType.ENTERPRISE)) {
            OjUserEnterpriseAttribute userEnterpriseAttribute = userEnterpriseAttributeMapper
                    .findOneByUserId(userId);
            user.setUserEnterpriseAttribute(userEnterpriseAttribute);
        }
        return user;
    }


    @Override
    public void addRelationShip(String phone, BigInteger id, UserType type, BigInteger parentUserId) {
        if (StringUtils.isEmpty(phone) || id==null || type==null || parentUserId==null){
            throw new DataSaveException("添加邀请关系失败，参数错误");
        }
        // 查询父用户详情信息
        OjUser parentUser = queryUserDetail(parentUserId);

        if (null != parentUser) {
            OjUserRelationShip relationShip = new OjUserRelationShip();
            relationShip.setId(Utils.id());
            relationShip.setUserId(id);
            relationShip.setParentUserId(parentUserId);
            relationShip.setCreateUserId(id);
            relationShip.setType(type);
            relationShip.setInviteePhone(phone);
            //add by jgYnag 初始化邀请和被邀请金额 start
            relationShip.setInviterAward((int) com.dlg.user.rpc.api.constant.DigitConstant.SHORT_ZERO);
            relationShip.setInviteeAward((int) com.dlg.user.rpc.api.constant.DigitConstant.SHORT_ZERO);
            //add by jgYnag 初始化邀请和被邀请金额  end
            addUserRelationship(relationShip);

            // 如果父用户为代理商，更新代理商发展统计
            if (parentUser.getUserEnterpriseAttribute() != null) {
                Short isAgent = parentUser.getUserEnterpriseAttribute().getIsAgent();
                if (null != isAgent && isAgent == 1) {
                    BigInteger userEnterpriseAttributeId = parentUser.getUserEnterpriseAttribute().getId();
                    // 用户企业代理属性 详情
                    OjUserEnterpriseAgentAttribute userEnterpriseAgentAttribute = queryEnterpriseAgentDetailByEnterpriseId(userEnterpriseAttributeId);

                    if (UserType.PERSONAL.equals(type)) {
                        userEnterpriseAgentAttribute.setPersonalAgentCount(
                                userEnterpriseAgentAttribute.getPersonalAgentCount() == null ? 1 : userEnterpriseAgentAttribute.getPersonalAgentCount() + 1);
                    } else if (UserType.ENTERPRISE.equals(type)) {
                        userEnterpriseAgentAttribute.setEnterpriseAgentCount(
                                userEnterpriseAgentAttribute.getEnterpriseAgentCount() == null ? 1 : userEnterpriseAgentAttribute.getEnterpriseAgentCount() + 1);
                    }
                    //更新代理商发展统计
                    updateEnterpriseAgentCountByUserId(parentUserId, userEnterpriseAgentAttribute);
                }
            }
        }
    }

    public OjUserEnterpriseAgentAttribute queryEnterpriseAgentDetailByEnterpriseId(BigInteger userEnterpriseAttributeId) {
        if (userEnterpriseAttributeId == null) {
            throw new DataFindException("userEnterpriseAttributeId is null");
        }
        return userEnterpriseAgentAttributeMapper.findByEnterpriseId(userEnterpriseAttributeId);
    }

    public void updateEnterpriseAgentCountByUserId(BigInteger userId,OjUserEnterpriseAgentAttribute ojUserEnterpriseAgentAttribute) {
        if (null == ojUserEnterpriseAgentAttribute) {
            throw new DataUpdateException("要更新的代理商对象为空");
        }
        if (null == ojUserEnterpriseAgentAttribute.getId()) {
            throw new DataUpdateException("要更新的代理商对象的id为空");
        }
        if (null == ojUserEnterpriseAgentAttribute.getUserEnterpriseAttributeId()) {
            throw new DataUpdateException("企业用户属性id为空！");
        }
        OjUserEnterpriseAgentAttribute userEnterpriseAgentAttribute = new OjUserEnterpriseAgentAttribute();
        Utils.copyNotNullObject(ojUserEnterpriseAgentAttribute,userEnterpriseAgentAttribute);
        if (userId != null) {
            userEnterpriseAgentAttribute.setModifyUserId(userId);
        }
        userEnterpriseAgentAttributeMapper.updateAgentCount(userEnterpriseAgentAttribute);
    }


    public BigInteger addUserRelationship(OjUserRelationShip userRelationShip) {
        if (null == userRelationShip) {
            throw new DataSaveException("要保存的对象为空");
        }
        if (null == userRelationShip.getUserId()) {
            throw new DataSaveException("用户Id为空");
        }
        if (null == userRelationShip.getParentUserId()) {
            throw new DataSaveException("父用户Id为空");
        }
        BigInteger id = Utils.id();
        userRelationShipMapper.save(userRelationShip);
        return id;
    }

    private BigInteger addUser(OjUser ojUser) {
        String msg = ojUser.validate();
        if (StringUtils.isNotEmpty(msg)){
            throw new DataSaveException(msg);
        }
        if (ojUser.getId()==null){
            throw new DataSaveException("要保存的用户id为空");
        }
        ojUser.setCreateUserId(ojUser.getCreateUserId()==null ? ojUser.getId() : ojUser.getCreateUserId());
        userMapper.save(ojUser);
        return ojUser.getId();
    }

    private BigInteger addEnterpriseUser(OjUserEnterpriseAttribute enterpriseAttribute) {
        if (null == enterpriseAttribute) {
            throw new DataSaveException("要保存的企业用户信息为空");
        }
        if (enterpriseAttribute.getId()==null){
            throw new DataSaveException("要保存的企业用户id为空");
        }
        if (null == enterpriseAttribute.getUserId()) {
            throw new DataSaveException("要保存的企业用户UserId为空");
        }
        if (userEnterpriseAttributeMapper.findOneByUserId(enterpriseAttribute.getUserId()) != null) {
            throw new DataSaveException("该用户已经存在企业信息");
        }
        userEnterpriseAttributeMapper.save(enterpriseAttribute);
        return enterpriseAttribute.getId();
    }

    private BigInteger addPersonalUser(OjUserPersonalAttribute ojUserPersonalAttribute) {
        if (null == ojUserPersonalAttribute) {
            throw new DataSaveException("要保存的个人用户信息为空");
        }
        if (ojUserPersonalAttribute.getId()==null){
            throw new DataSaveException("要保存的个人用户id为空");
        }
        if (null == ojUserPersonalAttribute.getUserId()) {
            throw new DataSaveException("要保存的个人用户UserId为空");
        }
        BigInteger userId = ojUserPersonalAttribute.getUserId();
        if (userPersonalAttributeMapper.findOneByUserId(userId) != null) {
            throw new DataSaveException("该用户已经存在个人信息");
        }
        userPersonalAttributeMapper.save(ojUserPersonalAttribute);
        return ojUserPersonalAttribute.getId();
    }

}
